import React, { Dispatch, useEffect, useRef, useState } from "react";
import {
  NativeSyntheticEvent,
  TextInput,
  TextInputFocusEventData,
} from "react-native";
import styles from "./index.style";
import { SessionType } from "@/types/chat-session";
import { DrawerType } from "@/components/Chat/ChatDetail";
import { useTheme } from "@/contexts/ThemeContext";
import { useTypingStatus } from "@/hooks/chat/chat-detail-typing";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
interface ChatInputBarProps {
  inputText: string;
  setInputText: Dispatch<React.SetStateAction<string>>;
  sessionId: string;
  sessionType: SessionType;
  setShowDrawerType: Dispatch<React.SetStateAction<DrawerType>>;
  replyTo?: {
    messageId: string;
    senderName: string;
    content: string;
  } | null;
  onCancelReply?: () => void;
}
// 停止输入时间
const TYPING_TIMEOUT = 500; // 0.5秒后认为停止输入

export const ChatInputBar = React.forwardRef<TextInput, ChatInputBarProps>(
  (
    {
      inputText,
      setInputText,
      sessionId,
      sessionType,
      setShowDrawerType,
      replyTo,
      onCancelReply,
    },
    ref
  ) => {
    const { colors } = useTheme();
    const [typing, setTyping] = useState(false);
    const textInputRef = useRef<TextInput>(null);
    const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    const [_, setTypingStatus] = useTypingStatus();
    const {updateSession} = useChatSessionActions()

    useEffect(() => {
      if (ref && typeof ref === "object") {
        ref.current = textInputRef.current;
      }
    }, [ref]);


    useEffect(() => {
      // 更新草稿
      updateSession({
        sessionId,
        draft: inputText.trim() || null, // 如果输入框为空，则清除草稿
      })
    }, [inputText]);

    const resetTyping = async () => {
      typingTimeoutRef.current = setTimeout(() => {
        setTyping(false);
      }, TYPING_TIMEOUT);
    };

    const handleInputChange = (text: string) => {
      setInputText(text);

      if (!typing) {
        setTyping(true);
      }

      if (typingTimeoutRef.current) {
        clearTimeout(typingTimeoutRef.current);
      }

      resetTyping();
    };

    const handleFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
      setShowDrawerType(null);
    };

    useEffect(() => {
      if (sessionType === SessionType.SINGLE) {
        setTypingStatus({ sessionId, typing });
      }
      return () => {
        if (typingTimeoutRef.current) {
          clearTimeout(typingTimeoutRef.current);
        }
      };
    }, [typing]);

    return (
      <TextInput
        ref={textInputRef}
        placeholderTextColor={colors.text.hint}
        style={[
          styles.textInput,
          {
            color: colors.text.primary,
            borderColor: colors.border.medium,
            backgroundColor: colors.inputBackground,
          },
        ]}
        value={inputText}
        onPressIn={() => setShowDrawerType(null)}
        onChangeText={handleInputChange}
        onFocus={handleFocus}
        placeholder="请输入文字"
      />
    );
  }
);
